package cn.gdut.chengcai.base;

import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;

public class RequestUtil {

	public static String getRemoteHost(HttpServletRequest request) {
		return request.getRemoteHost();
	}

	/**
	 * 返回请求的完整URL
	 */
	public static String getRequestURL(HttpServletRequest request) {
		StringBuffer sb = request.getRequestURL();
		if (request.getQueryString() != null) {
			sb.append('?');
			sb.append(request.getQueryString());
		}
		return sb.toString();
	}

	/**
	 * 返回请求的URI
	 */
	public static String getRequestURI(HttpServletRequest request) {
		String requestURI = request.getRequestURI();
		String contextPath = request.getContextPath();
		return requestURI.replaceAll(contextPath, "");
	}

	/**
	 * 返回请求的URI
	 */
	public static String getRequestURI(HttpServletRequest request, String uri) {
		String contextPath = request.getContextPath();
		return uri.replaceAll(contextPath, "");
	}

	/**
	 * 返回请求的URL的根目录
	 */
	public static String getRequestURLRoot(HttpServletRequest request) {
		String requestURL = request.getRequestURL().toString();
		String requestURI = request.getRequestURI();
		String contextPath = request.getContextPath();
		String requestURLRoot = requestURL.replaceAll(requestURI.replaceAll(contextPath, ""), "");
		return requestURLRoot;
	}

	/**
	 * 获取Request的参数
	 */
	public static String getParameter(HttpServletRequest request, String param) {
		String result = null;
		try {
			result = request.getParameter(param);
			if (StringUtils.isEmpty(result) == false) {
				// result = new String(result.getBytes("ISO-8859-1"), "UTF-8");
				result = result.trim();
			}
		} catch (Exception e) {
			// e.printStackTrace();
		}
		return result;
	}

	/**
	 * 获取Request的参数
	 */
	public static String getParameterFromGet(HttpServletRequest request, String param) {
		String result = null;
		try {
			result = request.getParameter(param);
			if (StringUtils.isEmpty(result) == false) {
				result = new String(result.getBytes("ISO-8859-1"), "UTF-8");
				result = result.trim();
			}
		} catch (Exception e) {
			// e.printStackTrace();
		}
		return result;
	}

	/**
	 * 重设Tonken操作
	 */
	public static void resetToken(HttpSession session) {
		session.setAttribute("token", UUID.randomUUID().toString());
	}

}
